<?php
/**
 * Created by ephp
 * User: 22071
 * Date: 2019/6/15
 * Email: <zhendongdong@foxmail.com>
 */

namespace paper\relation;


use paper\Relation;

class BelongTo extends Relation
{

    /**
     * 预查询
     * @param $result
     * @return array|bool|mixed
     * @throws \Exception
     */
    public function prepareRelation(&$result)
    {
        if (!$result)
            return [];
        $keys = array_column($result, $this->localKey);
        $list = $this->query->where($this->foreignKey, 'in', $keys)->where($this->where)->index($this->foreignKey)->select();
        return $list;
    }

    /**
     * 获取查询条件
     * @return \paper\pdo\Query
     */
    protected function constraint()
    {
        $v = $this->model->getData($this->localKey);
        return $this->query->where([$this->foreignKey => $v])->where($this->where);
    }

    /**
     * @return array|bool|mixed|void
     * @throws \Exception
     */
    public function getData()
    {
        return $this->constraint()->find();
    }
}